import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getCartList, addToCart, updateCart, deleteCart, clearCart as clearCartAPI, getCartCount } from '@/api/cart'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore('cart', () => {
  const items = ref([])
  const loading = ref(false)
  const cartCount = ref(0)

  // 购物车商品总数
  const totalCount = computed(() => {
    if (!items.value || items.value.length === 0) return 0
    return items.value.reduce((sum, item) => sum + (Number(item.quantity) || 0), 0)
  })

  // 购物车总价
  const totalPrice = computed(() => {
    if (!items.value || items.value.length === 0) return 0
    return items.value.reduce((sum, item) => {
      const price = Number(item.price) || 0
      const quantity = Number(item.quantity) || 0
      return sum + (price * quantity)
    }, 0)
  })

  // 可购买商品总价（只计算上架且库存充足的商品）
  const availableTotalPrice = computed(() => {
    if (!items.value || items.value.length === 0) return 0
    return items.value
      .filter(item => item.status === 1 && item.stock >= item.quantity)
      .reduce((sum, item) => {
        const price = Number(item.price) || 0
        const quantity = Number(item.quantity) || 0
        return sum + (price * quantity)
      }, 0)
  })

  // 选中商品的总价
  const selectedTotalPrice = computed(() => {
    if (!items.value || items.value.length === 0) return 0
    return items.value
      .filter(item => item.checked && item.status === 1 && item.stock >= item.quantity)
      .reduce((sum, item) => {
        const price = Number(item.price) || 0
        const quantity = Number(item.quantity) || 0
        return sum + (price * quantity)
      }, 0)
  })

  // 选中商品的数量
  const selectedCount = computed(() => {
    if (!items.value || items.value.length === 0) return 0
    return items.value.filter(item => item.checked).length
  })

  // 加载购物车列表
  const loadCart = async () => {
    loading.value = true
    try {
      const res = await getCartList()
      if (res.code === 200) {
        items.value = (res.data || []).map(item => ({
          ...item,
          checked: false, // 添加选中状态
          price: Number(item.price) || 0,
          quantity: Number(item.quantity) || 0,
          stock: Number(item.stock) || 0,
          subtotal: Number(item.subtotal) || 0
        }))
        cartCount.value = items.value.length
      } else {
        items.value = []
        cartCount.value = 0
      }
    } catch (error) {
      console.error('加载购物车失败:', error)
      items.value = []
      cartCount.value = 0
      // 如果是401错误（未登录），不显示错误提示
      if (error.response?.status !== 401) {
        ElMessage.error('加载购物车失败')
      }
    } finally {
      loading.value = false
    }
  }

  // 添加商品到购物车
  const addItem = async (productId, quantity = 1) => {
    try {
      const res = await addToCart({ productId, quantity })
      if (res.code === 200) {
        ElMessage.success('添加成功')
        await loadCart() // 重新加载购物车
        await updateCartCount()
        return true
      } else {
        ElMessage.error(res.message || '添加失败')
        return false
      }
    } catch (error) {
      console.error('添加购物车失败:', error)
      ElMessage.error(error.response?.data?.message || '添加购物车失败')
      return false
    }
  }

  // 更新商品数量
  const updateQuantity = async (cartId, quantity) => {
    try {
      const res = await updateCart({ id: cartId, quantity })
      if (res.code === 200) {
        // 更新本地数据
        const item = items.value.find(item => item.id === cartId)
        if (item) {
          item.quantity = quantity
        }
        return true
      } else {
        ElMessage.error(res.message || '更新失败')
        return false
      }
    } catch (error) {
      console.error('更新购物车失败:', error)
      ElMessage.error(error.response?.data?.message || '更新购物车失败')
      return false
    }
  }

  // 移除商品
  const removeItem = async (cartId) => {
    try {
      const res = await deleteCart(cartId)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        // 从本地数据中移除
        const index = items.value.findIndex(item => item.id === cartId)
        if (index > -1) {
          items.value.splice(index, 1)
        }
        await updateCartCount()
        return true
      } else {
        ElMessage.error(res.message || '删除失败')
        return false
      }
    } catch (error) {
      console.error('删除购物车失败:', error)
      ElMessage.error(error.response?.data?.message || '删除购物车失败')
      return false
    }
  }

  // 清空购物车
  const clearCartItems = async () => {
    try {
      const res = await clearCartAPI()
      if (res.code === 200) {
        ElMessage.success('清空成功')
        items.value = []
        cartCount.value = 0
        return true
      } else {
        ElMessage.error(res.message || '清空失败')
        return false
      }
    } catch (error) {
      console.error('清空购物车失败:', error)
      ElMessage.error(error.response?.data?.message || '清空购物车失败')
      return false
    }
  }

  // 更新购物车数量（显示在导航栏）
  const updateCartCount = async () => {
    try {
      const res = await getCartCount()
      if (res.code === 200) {
        cartCount.value = Number(res.data) || 0
      } else {
        cartCount.value = 0
      }
    } catch (error) {
      console.error('获取购物车数量失败:', error)
      cartCount.value = 0
    }
  }

  // 全选/取消全选
  const toggleSelectAll = (checked) => {
    items.value.forEach(item => {
      // 只有上架且库存充足的商品才能被选中
      if (item.status === 1 && item.stock >= item.quantity) {
        item.checked = checked
      }
    })
  }

  // 切换单个商品的选中状态
  const toggleItemSelect = (cartId) => {
    const item = items.value.find(item => item.id === cartId)
    if (item && item.status === 1 && item.stock >= item.quantity) {
      item.checked = !item.checked
    }
  }

  // 获取选中的商品
  const getSelectedItems = () => {
    return items.value.filter(item => item.checked)
  }

  // 重置购物车（清空本地数据，用于登出）
  const reset = () => {
    items.value = []
    cartCount.value = 0
  }

  // 初始化购物车（登录后调用）
  const init = async () => {
    try {
      await updateCartCount()
    } catch (error) {
      console.error('初始化购物车失败:', error)
    }
  }

  return {
    items,
    loading,
    cartCount,
    totalCount,
    totalPrice,
    availableTotalPrice,
    selectedTotalPrice,
    selectedCount,
    loadCart,
    addItem,
    updateQuantity,
    removeItem,
    clearCartItems,
    updateCartCount,
    toggleSelectAll,
    toggleItemSelect,
    getSelectedItems,
    reset,
    init
  }
})
















